package com.god.gl.ble.test;

import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.le.BluetoothLeScanner;
import android.bluetooth.le.ScanCallback;
import android.bluetooth.le.ScanResult;
import android.bluetooth.le.ScanSettings;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.FragmentActivity;

import com.god.gl.ble.R;
import com.njzdr.common.BluetoothManager;

import java.util.ArrayList;
import java.util.List;

/**
 * 低功耗蓝牙，配对 连接，搜索功能
 *
 * @author gl
 * @date 2021/3/8
 * @desc
 */
public class BluetoothBlueTestActivity extends FragmentActivity {
    private static final int REQUEST_CODE_PERMISSION_LOCATION = 2;
    private BluetoothAdapter mBluetoothAdapter;
    private BluetoothLeScanner mBluetoothLeScanner;
    private boolean isConnect = false;
    private ScanCallback mScanCallback = new ScanCallback() {
        @RequiresApi(api = Build.VERSION_CODES.M)
        @Override
        public void onScanResult(int callbackType, ScanResult result) {
            //super.onScanResult(callbackType, result);
            //对扫描到的设备进行操作。如：获取设备信息。
            Log.e("result", result.getDevice().getName() + "--" + result.getDevice().getAddress());
            if ((!isConnect) && "蓝牙名称".equals(result.getDevice().getName())) {
                isConnect = true;
                mBluetoothLeScanner.stopScan(mScanCallback);
                Log.d("result", "正在连接遥控器");
                BluetoothDevice bluetoothDevice = result.getDevice();
                bluetoothDevice.createBond();
                bluetoothDevice.connectGatt(BluetoothBlueTestActivity.this, false,
                        new MyGattCallBack(bluetoothDevice, BluetoothBlueTestActivity.this), BluetoothDevice.TRANSPORT_LE);
            }
        }

        @Override
        public void onBatchScanResults(List<ScanResult> results) {
            // super.onBatchScanResults(results);
            Log.e("onBatchScanResults", "onBatchScanResults");
        }

        @Override
        public void onScanFailed(int errorCode) {
            //   super.onScanFailed(errorCode);
            Log.e("onScanFailed", "onScanFailed");
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test);
        checkPermissions();

        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        mBluetoothLeScanner = mBluetoothAdapter.getBluetoothLeScanner();

        //创建ScanSettings的build对象用于设置参数
        ScanSettings.Builder builder = new ScanSettings.Builder()
                //设置高功耗模式
                .setScanMode(ScanSettings.SCAN_MODE_BALANCED);
        //android 6.0添加设置回调类型、匹配模式等
        if (Build.VERSION.SDK_INT >= 23) {
            //定义回调类型
            builder.setCallbackType(ScanSettings.CALLBACK_TYPE_ALL_MATCHES);
            //设置蓝牙LE扫描滤波器硬件匹配的匹配模式
            builder.setMatchMode(ScanSettings.MATCH_MODE_STICKY);
        }
        //芯片组支持批处理芯片上的扫描
        if (mBluetoothAdapter.isOffloadedScanBatchingSupported()) {
            //设置蓝牙LE扫描的报告延迟的时间（以毫秒为单位）
            //设置为0以立即通知结果
            builder.setReportDelay(0L);
        }
        mBluetoothLeScanner.startScan(null, builder.build(), mScanCallback);

        Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public void run() {
                //10秒后执行Runnable中的run方法
                mBluetoothLeScanner.stopScan(mScanCallback);
                List<BluetoothDevice> pairList = BluetoothManager.getInstance().getPairDeviceList();
                if (pairList.size() > 0) {
                    Log.d("###result", "强制连接遥控器");
                    BluetoothDevice device = pairList.get(0);
                    device.connectGatt(BluetoothBlueTestActivity.this, false,
                            new MyGattCallBack(device, BluetoothBlueTestActivity.this), BluetoothDevice.TRANSPORT_LE);
                }
            }
        }, 3000);


    }


    private void checkPermissions() {
     /*   if (!HidConnectUtil.getInstance().isSupportBluetooth()) {
            return;
        }*/
        String[] permissions = {Manifest.permission.ACCESS_FINE_LOCATION};
        List<String> permissionDeniedList = new ArrayList<>();
        for (String permission : permissions) {
            int permissionCheck = ContextCompat.checkSelfPermission(this, permission);
            if (permissionCheck == PackageManager.PERMISSION_GRANTED) {
                Log.d("permission", "权限申请成功");
            } else {
                permissionDeniedList.add(permission);
            }
        }
        if (!permissionDeniedList.isEmpty()) {
            String[] deniedPermissions = permissionDeniedList.toArray(new String[permissionDeniedList.size()]);
            ActivityCompat.requestPermissions(this, deniedPermissions, REQUEST_CODE_PERMISSION_LOCATION);
        }
    }


    @Override
    public final void onRequestPermissionsResult(int requestCode,
                                                 @NonNull String[] permissions,
                                                 @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case REQUEST_CODE_PERMISSION_LOCATION:
                if (grantResults.length > 0) {
                    for (int i = 0; i < grantResults.length; i++) {
                        if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
                        }
                    }
                }
                break;
        }
    }

    class MyGattCallBack extends BluetoothGattCallback {

        private BluetoothDevice mBluetoothDevice;
        private Context mContext;
        //定义重连次数
        private int reConnectionNum = 0;
        //最多重连次数
        private int maxConnectionNum = 3;

        public MyGattCallBack(BluetoothDevice bluetoothDevice, Context context) {
            mBluetoothDevice = bluetoothDevice;
            mContext = context;
        }

        @RequiresApi(api = Build.VERSION_CODES.M)
        @Override
        public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
            super.onConnectionStateChange(gatt, status, newState);
            if (status == BluetoothGatt.GATT_SUCCESS) {
                //链接成功
                Log.d("###result", "连接遥控器成功");
            } else {
                //重连次数不大于最大重连次数
                if (reConnectionNum < maxConnectionNum) {
                    //重连次数自增
                    reConnectionNum++;
                    //连接设备
                    mBluetoothDevice.connectGatt(mContext, false, this, BluetoothDevice.TRANSPORT_LE);
                } else {
                    //断开连接，返回连接失败回调

                }
            }
        }
    }
} 